<template>
  <div>
    <div class="receipt-order-edit-wrapper app-container" style="margin-bottom: 60px" v-loading="loading">
      <el-card header="入库单基本信息">
        <el-form label-width="108px" :model="form" ref="receiptForm" :rules="rules">
          <el-row :gutter="24">
            <el-col :span="6">
              <el-form-item label="入库单号" prop="receiptOrderNo">
                <el-input style="width: 300px;" v-model="formattedTime" placeholder="入库单号" disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="15">
              <el-form-item style="margin-left: 330px;" label="供应商" prop="supplierNo">
                <el-select @click="seach" v-model="supplier" placeholder="请选择供应商" clearable filterable>
                  <el-option v-for="item in supplierList.value" :key="'ket-' + item.supplierNo"
                    :label="item.supplierName" :value="item.supplierNo" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="11">
              <el-form-item label="入库类型" prop="optType">
                <el-radio-group v-model="form.optType">
                  <el-radio-button v-for="item in wms_receipt_type" :key="item.value" :label="item.value">{{ item.label
                    }}</el-radio-button>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="业务单号" prop="orderNo">
                <el-input v-model="YWdate" placeholder="请输入业务单号" disabled type="text" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="11">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="form.remark" placeholder="备注...100个字符以内" rows="4" maxlength="100" type="textarea"
                  show-word-limit="show-word-limit"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <div style="display: flex;align-items: start">
                <el-form-item label="总金额" prop="totalAmount">
                  <el-input-number style="width:100%" v-model="handleAutoCalc" :precision="2" :min="0"/>
                </el-form-item>
              </div>
            </el-col>
          </el-row>
        </el-form>
      </el-card>
      <el-card header="商品明细" class="mt10">
        <div class="receipt-order-content">
          <div class="flex-space-between mb8">
            <label style="font-size: 18px;">批量操作</label>
            <p />
            <el-row>
              <el-col style="margin-left: 20px;" :span="8">
                <el-form-item label="仓库" prop="warehouseId">
                  <el-select @click="selectware" v-model="ware" placeholder="请选择仓库">
                    <el-option @click="seachware(dict.warehouseId)" v-for="dict in options"
                      :key="'key-' + dict.warehouseId" :label="dict.warehouseName"
                      :value="dict.warehouseId"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col style="margin-left: 20px;" :span="8">
                <el-form-item label="库区" prop="">
                  <el-select v-model="area" placeholder="请选择库区">
                    <el-option @click="" v-for="dict in areas" :key="'key-' + dict.areaNo" :label="dict.areaName"
                      :value="dict.areaNo"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col style="margin-left: 20px;" :span="4">
                <el-button style="margin-bottom: 10px;" type="primary" @click="batch" plain="plain"
                  size="default">确定</el-button>
              </el-col>
            </el-row>
            <hr style="margin-bottom: 10px;" />
            <el-button type="primary" plain="plain" size="default" @click="showAddItem" icon="Plus">添加商品</el-button>
          </div>
          <el-table :data="Data" border empty-text="暂无商品明细">
            <el-table-column label="物料名" align="center" prop="itemName"></el-table-column>
            <el-table-column label="物料编号" align="center" prop="itemNo"></el-table-column>
            <el-table-column label="物料类型" align="center" prop="itemType"></el-table-column>
            <el-table-column label="计划数量" align="center" prop="planQuantity">
              <template #default="scope">
                {{ queryParams.planQuantity }}
              </template>
            </el-table-column>
            <el-table-column label="实际数量" align="center" prop="real_quantity" width="180">
              <template #default="scope">
                <el-input-number :disabled="scope.row.disabled" v-model="scope.row.realQuantity" placeholder="数量" min="1"
                  @change="handleChangeQuantity"></el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="仓库" align="center" width="200" prop="warehouseId">
              <template #default="scope">
                <el-select  :disabled="scope.row.disabled" v-model="scope.row.warehouseId" @change="onWarehouseChange(scope.row)" placeholder="请选择仓库">
                  <el-option v-for="dict in options" :key="dict.warehouseId" :label="dict.warehouseName"
                    :value="dict.warehouseId"></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="库区" align="center" width="200" prop="areaId">
              <template #default="scope">
                <el-select :disabled="scope.row.disabled" v-model="scope.row.areaId" placeholder="请选择库区">
                  <el-option v-for="dict in scope.row.itemAreas" :key="dict.areaNo" :label="dict.areaName"
                    :value="dict.areaNo"></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="金额" align="center" width="150" prop="amount">
              <template v-model="scope.row.amount" #default="scope">
                <span>{{ scope.row.unitPrice * scope.row.realQuantity }} 元</span> 
              </template>
            </el-table-column>

            <el-table-column label="操作" align="center">
              <template #default="scope">
                <el-button :disabled="scope.row.disabled" type="primary" @click="deteleRow(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>
      <!-- 添加商品 -->
      <el-dialog :title="title" v-model="open" width="750px" append-to-body>
        <el-form ref="itemRef" :model="form2" label-width="100px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="物料名称" prop="itemName">
                <el-input v-model="form2.itemName" />
              </el-form-item>
            </el-col>
            <el-col :span="12" style="padding-left:10px;">
              <el-button type="primary" @click="queryItem">查询</el-button>
            </el-col>
          </el-row>
        </el-form>
        <el-table :data="item" border style="width: 42.3%;margin-left: 200px;" ref="multipleTableRef"
          @selection-change="handleSelectionChange">
          <el-table-column :selectable="selectable" type="selection" width="55" align="center" />
          <el-table-column prop="itemName" label="物料名称" width="150" />
          <el-table-column prop="unitPrice" label="物料单价" width="95px" />
        </el-table>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="addItem">确 定</el-button>
            <el-button @click="closeOpen">取 消</el-button>
          </div>
        </template>
      </el-dialog>

      <el-row style="margin-left:580px;margin-top: 20px;">
        <el-col :span="4">
          <div style="margin-right: 10px;">
            <el-button @click="doWarehousing" type="primary" class="ml10">增加</el-button>
          </div>
        </el-col>
        <el-col :span="4">
          <div>
            <el-button @click="cancel" class="mr10">取消</el-button>
          </div>
        </el-col>
      </el-row>
    </div>

  </div>
</template>

<script setup name="detail">
import { computed, getCurrentInstance, onMounted, reactive, ref, toRef, toRefs, watch } from "vue";
import { addOrder, getOrder, updateOrder } from "@/api/wms/order";
import { listItem } from "@/api/wms/item";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRoute } from "vue-router";
import { deleteId, delDetail, addDetail, getByIdDetail, updateDetail } from '@/api/wms/detail'
import { listSupplier } from '@/api/wms/supplier'
import { listWarehouse } from '@/api/wms/warehouse'
import { selectList } from '@/api/wms/area'

const da=ref(false)

const formattedTime = ref();
const YWdate = ref();
const options = ref([]);
const areas = ref([]);
const ItemAreas = ref([])
const sum = ref(0)
const ware = ref()
const area = ref()
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
let row = reactive([]);
const Data = ref([])
const rstate=ref()
const itemArea = ref()
const title = ref('')
const open = ref(false)
const item = ref([])
const supplier = ref()
const route = useRoute();
const supplierList = reactive([])
const { proxy } = getCurrentInstance();
const { wms_receipt_type } = proxy.useDict("wms_receipt_type");
const selectedSku = ref([])
const mode = ref(false)
const loading = ref(false)
const form2 = ref({
  itemName: "",
  itemNo: ""
});
const initFormData = {
  id: undefined,
  orderNo: undefined,
  optType: "1",
  merchantId: undefined,
  bizOrderNo: undefined,
  totalAmount: undefined,
  orderStatus: 0,
  remark: undefined,
  warehouseId: undefined,
  totalQuantity: 0,
}
const data = reactive({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    receiptOrderId: null,
    itemNo: null,
    itemName: null,
    itemType: null,
    planQuantity: 1,
    realQuantity: null,
    money: null,
    warehouseId: null,
    areaId: null,
    receiptOrderStatus: null,
    id: null
  },
  rules: {
    orderNo: [
      { required: true, message: "入库单号不能为空", trigger: "blur" }
    ],
    warehouseId: [
      { required: true, message: "请选择仓库", trigger: ['blur', 'change'] }
    ]
  }
});
const { form, rules, queryParams } = toRefs(data);



const multipleTableRef = ref();
const selectable = (row) => {
  if (Data.value.length === 0) {
    return true;
  } else {
    return !Data.value.some(item => row.id === item.id);
  }
};

//钩子函数
const myMethod = () => {
  if (queryParams.value.id != null) {
    seach()
    getOrder(queryParams.value.id).then(response => {
      formattedTime.value = response.data.receiptOrderNo
      YWdate.value = response.data.orderNo
      supplier.value = response.data.supplierId+''
      form.value.optType = response.data.receiptOrderType
      form.value.remark = response.data.remark
      sum.value = response.data.payableAmount
      rstate.value=response.data.receiptOrderStatus
    })
    getByIdDetail(queryParams.value.receiptOrderId).then(response => {
      selectware()
      response.rows.forEach(element => {
        console.log(element);
        let edititem = {
          'id':element.id,
          'itemName': element.item_name, 
          'itemNo': element.item_no,
          'itemType': element.item_type,
          'realQuantity': element.real_quantity,
          'warehouseId': element.warehouse_id+'',
          'areaId': element.area_id+'',
          'unitPrice': element.unit_price,
          'receiptOrderStatus':element.receipt_order_status,
          'API':1
        }
        onWarehouseChange(edititem)
        console.log(edititem.receiptOrderStatus);
        setTimeout(function(){
          Data.value.push(edititem)
        },500)
        if (edititem.receiptOrderStatus==3|| edititem.receiptOrderStatus==4||edititem.receiptOrderStatus==5) {
          edititem['disabled']=true
        }
      })
    })
  } else {
    formattedTime.value = formatCurrentTime()
    YWdate.value = formatCurrentTime()
  }


}
onMounted(myMethod)
// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.itemNo);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
  row.value = selection;
}
function seach() {
  listSupplier().then(response => {
    console.log(response.rows);
    supplierList.value = response.rows
  })
}
const cancel = async () => {
  await proxy?.$modal.confirm('确认取消编辑入库单吗？');
  close()
}
function closeOpen() {
  open.value = false
}
const close = () => {
  const obj = { path: "/order" };
  proxy?.$tab.closeOpenPage(obj);
}

function showAddItem() {
  open.value = true
  title.value = '添加物料'
}
function queryItem() {
  console.log(form2);
  listItem(form2.itemName).then(response => {
    console.log(response.rows)
    item.value = response.rows
  })
}
function addItem() {
  console.log(row.value)
  
  row.value.forEach(element => {
    Data.value.push(element)
  });
  for (let i = 0; i < Data.value.length; i++) {
    Data.value[i].realQuantity = 1
  }
  console.log(Data.value);
  open.value = false
  item.value = null

}

function deteleRow(row){
  if (queryParams.value.id!=null) {
    deleteId(row.id).then(response=>{
    })
  }
    Data.value = Data.value.filter(item => {
    return item.itemNo !== row.itemNo;
  })
}

// 初始化receipt-order-form ref
const receiptForm = ref()

const save = async () => {
  await proxy?.$modal.confirm('确认暂存入库单吗？');
  doSave()
}

const getParamsBeforeSave = (orderStatus) => {
  let details = []
  if (form.value.details?.length) {
    details = form.value.details.map(it => {
      return {
        id: it.id,
        skuId: it.itemSku.id,
        amount: it.amount,
        quantity: it.quantity,
        warehouseId: form.value.warehouseId,
      }
    })
  }

  return {
    id: form.value.id,
    orderNo: form.value.orderNo,
    orderStatus,
    optType: form.value.optType,
    merchantId: form.value.merchantId,
    bizOrderNo: form.value.bizOrderNo,
    remark: form.value.remark,
    totalAmount: form.value.totalAmount,
    totalQuantity: form.value.totalQuantity,
    warehouseId: form.value.warehouseId,
    details: details
  }
}

const doSave = async (orderStatus = 0) => {
  //验证receiptForm表单
  receiptForm.value?.validate((valid) => {
    // 校验
    if (!valid) {
      return ElMessage.error('请填写必填项')
    }
    const params = getParamsBeforeSave(orderStatus)
    loading.value = true
    if (params.id) {
      updateOrder(params).then((res) => {
        if (res.code === 200) {
          ElMessage.success(res.msg)
          close()
        } else {
          ElMessage.error(res.msg)
        }
      }).finally(() => {
        loading.value = false
      })
    } else {
      addOrder(params).then((res) => {
        if (res.code === 200) {
          ElMessage.success( res.msg)
          close()
        } else {
          ElMessage.error(res.msg)
        }
      }).finally(() => {
        loading.value = false
      })
    }
  })
}



const updateToInvalid = async () => {
  await proxy?.$modal.confirm('确认作废入库单吗？');
  doSave(-1)
}



// 获取入库单详情
const loadDetail = (id) => {
  loading.value = true
  getOrder(id).then((response) => {
    form.value = { ...response.data }
    if (response.data.details?.length) {
      selectedSku.value = response.data.details.map(it => {
        return {
          id: it.skuId
        }
      })
    }
    Promise.resolve();
  }).then(() => {
  }).finally(() => {
    loading.value = false
  })
}

const handleChangeQuantity = () => {

}



//查询仓库
function selectware() {
  listWarehouse().then(response => {
    console.log(response);
    options.value = response.rows
  })
}

//查询库区
function seachware(id) {
  selectList(id).then(response => {
    area.value = null
    areas.value = response.rows
  })
}
function onWarehouseChange(row) {
  // 查询当前行所选仓库的库区
  selectList(row.warehouseId).then(response => {
    row.itemAreas = response.rows; // 仅更新当前行的 itemAreas
    if(row.API=undefined){
      row.areaId = null; // 重置选中的库区
    }
    console.log(row.itemAreas);
    
  });
}
//表格查询库区
// function Dataseachware(id) {
//   console.log(id);
//   selectList(id).then(response => {
//     for (let i = 0; i < Data.value.length; i++) {
//       itemArea.value = null
//       ItemAreas.value = response.rows
//     }
//   })
// }
//批量
function batch() {
  console.log(area.value);
  for (const item of Data.value) {
    item.itemAreas = areas.value
    item.warehouseId = ware.value;
    item.areaNo = area.value; // 根据需要设置相应库区
    item.areaId = area.value; // 根据需要设置相应库区

    // 如果有特殊逻辑的话，可以根据 item.itemAreas 进行处理
  }
  console.log(Data.value);
}
//总价
const handleAutoCalc = computed(() => {
  sum.value = 0
  for (let i = 0; i < Data.value.length; i++) {
    sum.value += Data.value[i].realQuantity * Data.value[i].unitPrice
  }
  return sum

})

const handleDeleteDetail = (row, index) => {
  if (row.id) {
    proxy.$modal.confirm('确认删除本条商品明细吗？如确认会立即执行！').then(function () {
      loading.value = true
      return delDetail(row.id);
    }).then(() => {
      form.value.details.splice(index, 1)
      proxy.$modal.msgSuccess("删除成功");
    }).finally(() => {
      loading.value = false
    });
  } else {
    form.value.details.splice(index, 1)
  }
  const indexOfSelected = selectedSku.value.findIndex(it => row.itemSku.id === it.id)
  selectedSku.value.splice(indexOfSelected, 1)
}
//返回年月日
function formatCurrentTime() {
  const date = new Date();

  // 获取年份
  const year = date.getFullYear();
  // 获取月份（需要补齐两位数，从0开始所以要加1）
  const month = String(date.getMonth() + 1).padStart(2, '0');
  // 获取日期
  const day = String(date.getDate()).padStart(2, '0');
  // 获取小时
  const hours = String(date.getHours()).padStart(2, '0');
  // 获取分钟
  const minutes = String(date.getMinutes()).padStart(2, '0');
  // 获取秒数
  const seconds = String(date.getSeconds()).padStart(2, '0');

  // 连接成需要的格式
  return `${year}${month}${day}${hours}${minutes}${seconds}`;
}
const doWarehousing = async () => {
  await proxy?.$modal.confirm('确认入库吗？');
  let param1 = {
    'receiptOrderNo': formattedTime.value,
    'receiptOrderType': form.value.optType,
    'supplierId': supplier.value,
    'orderNo': YWdate.value,
    'payableAmount': sum.value,
    'receiptOrderStatus': 1,
    'remark': form.value.remark
  }

  if (queryParams.value.id != null) {
    param1.receiptOrderStatus=rstate.value
    updateOrder(param1).then(response => {
      param1.receiptOrderNo=queryParams.value.receiptOrderId
      ElMessage.success('操作成功');
    })
  } else {
    addOrder(param1).then(response => {
      ElMessage.success('操作成功');
    })
  }


  for (let i = 0; i < Data.value.length; i++) {
    if (Data.value[i].receiptOrderStatus==1 || Data.value[i].receiptOrderStatus==undefined) {
      let param2 = {
      'receiptOrderId': formattedTime.value,
      'itemId': Data.value[i].itemNo,
      'planQuantity': queryParams.value.planQuantity,
      'realQuantity': Data.value[i].realQuantity,
      'money': Data.value[i].realQuantity * Data.value[i].unitPrice,
      'warehouseId': Data.value[i].warehouseId,
      'areaId': Data.value[i].areaId,
      'receiptOrderStatus': 1
      }
      if (queryParams.value.id != null) {
      param2.receiptOrderId=queryParams.value.receiptOrderId
      updateDetail(param2).then(response => {
        close()
      })
      }else{
        addDetail(param2).then(response => {
          close()
        })
      }
  }
  }
}
queryParams.value.id = route.query && route.query.id
queryParams.value.receiptOrderId = route.query && route.query.receiptOrderNo

</script>
